package cn.mesmile.activity.listener1;

import cn.mesmile.activity.util.CustomSpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiActivityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.Task;
import org.activiti.spring.integration.Activiti;
import org.springframework.stereotype.Component;
import org.w3c.dom.ls.LSException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zb
 * @date 2021/01/27 17:10
 * @Description 节点完成监听器
 */
@Component
public class ActivityCompleteListener implements ActivitiEventListener {

    @Override
    public void onEvent(ActivitiEvent event) {
        ActivitiEventType type = event.getType();
        if(ActivitiEventType.ACTIVITY_COMPLETED.equals(type)){
            if (event instanceof ActivitiActivityEventImpl) {
                ActivitiActivityEventImpl eventImpl = (ActivitiActivityEventImpl) event;
                // 这里 activityId 等于 taskDefinitionId
                String activityId = eventImpl.getActivityId();
                String processInstanceId = eventImpl.getProcessInstanceId();
                // 当前完成的任务
                String executionId = eventImpl.getExecutionId();
                TaskService taskService = CustomSpringUtils.getBean(TaskService.class);
                List<Task> list = taskService.createTaskQuery()
                        .taskDefinitionKey(activityId)
                        .processInstanceId(processInstanceId)
                        .list();
                // 通知PS审批通过， 大于1代表有多个实例
                if (list != null && list.size() > 1){
                    for (Task task : list) {
                        String executionIdStr = task.getExecutionId();
                        // 这里排查当前完成人的任务，避免重复通知
                        if ( !Objects.equals(executionId,executionIdStr) ){
                            // todo 通知PS审批通过

                        }
                    }
                }
            }
        }
    }

    /**
     * 监听异常处理策略
     * @return
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }

}
